package com.heima.search.service;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.search.pojos.ApUserSearch;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * create 2023/6/23 21:24
 */


@Slf4j
@Service
public class ApUserSearchServiceImpl implements ApUserSearchService{

    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 保存用户搜索历史记录
     *
     * @param keyword
     * @param userId
     */
    @Async
    @Override
    public void insert(String keyword, Integer userId) {

        //1.根据用户Id和关键词查询，有则更新创建时间
        Query query = Query.query(Criteria.where("userId").is(userId).and("keyword").is(keyword));
        ApUserSearch userSearch = mongoTemplate.findOne(query, ApUserSearch.class);
        if (userSearch != null) {
            userSearch.setCreatedTime(new Date());
            mongoTemplate.save(userSearch);
            return;
        }
        //2.没有则判断该用户的历史记录是否小于10
        userSearch=new ApUserSearch();
        userSearch.setUserId(userId);
        userSearch.setCreatedTime(new Date());
        userSearch.setKeyword(keyword);
        Query query1 = Query.query(Criteria.where("userId").is(userId)).with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApUserSearch> userSearchList = mongoTemplate.find(query1, ApUserSearch.class);
        if (userSearchList != null && userSearchList.size() >= 10) {
            //2.1.大于10条则替换最早的记录
            ApUserSearch lastUserSearch = userSearchList.get(userSearchList.size() - 1);
          mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(lastUserSearch.getId())), userSearch);
        }else {
            //2.2.小于10条则新增
            mongoTemplate.save(userSearch);
        }
    }

    @Override
    public ResponseResult findUserSearch() {

        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.okResult(null);
        }
        List<ApUserSearch> userSearchList = mongoTemplate.find(Query.query(Criteria.where("userId").is(user.getId())).with(Sort.by(Sort.Direction.DESC,"createdTime")), ApUserSearch.class);
        return ResponseResult.okResult(userSearchList);
    }

    @Override
    public ResponseResult delUserSearch(HistorySearchDto dto) {

        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        mongoTemplate.remove(Query.query(Criteria.where("userId").is(user.getId()).and("id").is(dto.getId())),ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
